#import "ALCanvasPage.h"
#import "ALTimelineElement.h"


#pragma mark Constants
const CGFloat ALTimelineViewPageWidth = 500.0f;


#pragma mark -
@interface ALCanvasPage ()
@property (nonatomic, retain) NSArray *elements;
@end


#pragma mark -
@implementation ALCanvasPage

@synthesize leftBoundary;
@synthesize maxX;
@synthesize elements;


-(id)init {
	return [self initWithLeftBoundary:0];
}

-(id)initWithLeftBoundary:(CGFloat)leftX {
	if (!(self = [super init]))
		return nil;
	[self setLeftBoundary:leftX];
	[self setMaxX:leftX + ALTimelineViewPageWidth];
	[self setElements:[NSArray array]];
	return self;
}

-(void)addElement:(ALTimelineElement *)element atRect:(NSRect)elementRect {
	if (!element)
		return;
	NSArray *currentElements = [self elements];
	[self setElements:[currentElements arrayByAddingObject:element]];
	[self setMaxX:MAX([self maxX], NSMaxX(elementRect))];
}

-(CGFloat)rightBoundary {
	return [self leftBoundary] + ALTimelineViewPageWidth;
}

-(ALTimelineElement *)elementAtPoint:(NSPoint)aPoint {
	if (aPoint.x < [self leftBoundary] || aPoint.x > [self maxX])
		return nil;
	for (ALTimelineElement *element in [self elements]) {
		NSRect elementRect = [element currentPosition];
		if (NSPointInRect(aPoint, elementRect))
			return element;
	}
	return nil;
}

-(BOOL)pointInPage:(NSPoint)aPoint {
	if (aPoint.x >= [self leftBoundary] && aPoint.x <= [self rightBoundary])
		return YES;
	return NO;
}

-(BOOL)pointInExtendedPage:(NSPoint)aPoint {
	if (aPoint.x >= [self leftBoundary] && aPoint.x <= [self maxX])
		return YES;
	return NO;
}

@end
